const dayjs = require('dayjs');
const { observable, action } = require('mobx-miniprogram');
const cloudHelper = require('../../helpers/cloud_helper.js');
const pageHelper = require('../../helpers/page_helper.js');
const cacheHelper = require('../../helpers/cache_helper.js');
const timeHelper = require('../../helpers/time_helper.js');
const { standardizeGlobalStore } = require('../helpers/store_standardizer.js');

// 定义缓存键
const CACHE_FOOT = 'CACHE_FOOT';

// 定义API路由
const FAV_API = {
  LIST: 'fav/list',      // 获取收藏列表
  IS_FAV: 'fav/is_fav',  // 检查是否收藏
  UPDATE: 'fav/update',  // 更新收藏状态
  DEL: 'fav/del'         // 删除收藏
};

// 收藏Store
export const favStore = observable({
  // 收藏列表数据
  favList: {
    list: [],
    total: 0,
  },
  
  // 当前收藏状态 (-1: 未知, 0: 未收藏, 1: 已收藏)
  isFav: -1,
  
  // 加载状态
  loading: false,
  
  // 最后加载时间 - 用于缓存控制
  lastLoadTime: null,
  
  // 当前操作对象
  currentOid: '',
  
  // 是否需要刷新
  needRefresh: false,
  
  // 初始化
  init: action(function() {
    this.favList = {
      list: [],
      total: 0,
    };
    this.isFav = -1;
    this.loading = false;
    this.lastLoadTime = null;
    this.currentOid = '';
    this.needRefresh = false;
  }),
  
  // 加载收藏列表
  loadFavList: action(async function(isRefresh = false) {
    if (this.loading && !isRefresh) return;
    
    try {
      this.loading = true;
      
      // 判断是否刷新
      if (isRefresh) {
        this.needRefresh = false;
        this.lastLoadTime = null;
      }
      
      // 调用云函数获取收藏列表
      const opts = { title: '加载中' };
      const result = await cloudHelper.callCloudData(FAV_API.LIST, {}, opts);
      
      if (result && result.list) {
        this.favList = {
          list: result.list,
          total: result.total
        };
        this.lastLoadTime = dayjs().valueOf();
      }
      
      return this.favList;
    } catch (e) {
      console.error('加载收藏列表失败', e);
      return null;
    } finally {
      this.loading = false;
    }
  }),
  
  // 检查是否收藏
  checkIsFav: action(async function(oid, type = '') {
    if (!oid) return false;
    
    this.currentOid = oid;
    this.isFav = -1;
    
    try {
      // 调用云函数检查收藏状态
      const params = { oid, type };
      const result = await cloudHelper.callCloudSumbit(FAV_API.IS_FAV, params, { title: 'bar' });
      
      if (result && result.data) {
        this.isFav = result.data.isFav;
      }
      
      return this.isFav;
    } catch (error) {
      console.error('检查收藏状态失败', error);
      return -1;
    }
  }),
  
  // 更新收藏状态
  updateFav: action(async function(oid, title, type, isFav) {
    if (!oid || !title || !type) return false;
    
    // 获取当前页面路径
    const path = pageHelper.getCurrentPageUrlWithArgs();
    if (!path) return false;
    
    try {
      // 设置参数
      const params = {
        oid,
        title,
        type,
        path
      };
      
      // 设置选项
      const opts = {
        title: (isFav == 0) ? '收藏中' : '取消中'
      };
      
      // 调用更新收藏云函数
      const result = await cloudHelper.callCloudSumbit(FAV_API.UPDATE, params, opts);
      
      if (result && result.data) {
        this.isFav = result.data.isFav;
        this.needRefresh = true;
        return true;
      }
      
      return false;
    } catch (e) {
      console.error('更新收藏状态失败', e);
      return false;
    }
  }),
  
  // 删除收藏
  deleteFav: action(async function(oid) {
    if (!oid) return false;
    
    try {
      const result = await cloudHelper.callCloudSumbit(FAV_API.DEL, { oid });
      
      if (result) {
        // 更新本地数据
        this.favList.list = this.favList.list.filter(item => item.FAV_OID !== oid);
        this.favList.total--;
        return true;
      }
      
      return false;
    } catch (err) {
      console.error('删除收藏失败', err);
      return false;
    }
  })
});

// 足迹Store
export const footStore = observable({
  // 足迹列表
  footList: [],
  
  // 加载状态
  loading: false,
  
  // 初始化
  init: action(function() {
    this.footList = [];
    this.loading = false;
  }),
  
  // 加载足迹列表
  loadFootList: action(function() {
    if (this.loading) return;
    
    try {
      this.loading = true;
      
      // 从缓存获取足迹数据
      let foot = cacheHelper.get(CACHE_FOOT);
      
      if (foot) {
        // 处理时间显示
        for (let i = 0; i < foot.length; i++) {
          foot[i].time = timeHelper.timestamp2Time(foot[i].time);
        }
        
        this.footList = foot;
      } else {
        this.footList = [];
      }
      
      return this.footList;
    } catch (e) {
      console.error('加载足迹列表失败', e);
      return [];
    } finally {
      this.loading = false;
    }
  }),
  
  // 添加足迹记录
  addFoot: action(function(type, title, size = 60, expire = 86400 * 365 * 3) {
    if (!type || !title) return;
    
    try {
      // 获取当前页面路径
      const path = pageHelper.getCurrentPageUrlWithArgs();
      if (!path) return;
      
      // 获取当前足迹列表
      let foot = cacheHelper.get(CACHE_FOOT, []);
      
      // 删除已存在的相同路径记录
      for (let k = 0; k < foot.length; k++) {
        if (path === foot[k].path) {
          foot.splice(k, 1);
          break;
        }
      }
      
      // 添加新记录到列表头部
      const newFoot = {
        path,
        type,
        title,
        time: timeHelper.time()
      };
      
      foot.unshift(newFoot);
      
      // 控制列表大小，删除多余记录
      if (foot.length > size) {
        foot.splice(foot.length - 1, 1);
      }
      
      // 更新缓存
      cacheHelper.set(CACHE_FOOT, foot, expire);
      
      // 更新store数据
      this.loadFootList();
      
      return foot;
    } catch (e) {
      console.error('添加足迹失败', e);
      return [];
    }
  }),
  
  // 清空足迹
  clearFootList: action(function() {
    try {
      // 清除缓存
      cacheHelper.remove(CACHE_FOOT);
      
      // 清空列表
      this.footList = [];
      return true;
    } catch (e) {
      console.error('清空足迹失败', e);
      return false;
    }
  })
});

// 应用标准化Store
export const standardizedFavStore = standardizeGlobalStore(favStore, 'fav');
export const standardizedFootStore = standardizeGlobalStore(footStore, 'foot');

export default {
  favStore: standardizedFavStore,
  footStore: standardizedFootStore
}; 